package com.lianzai.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.lianzai.camera.service.CameraBlackAndWhiteService;
import com.lianzai.car.domain.CarLogDO;
import com.lianzai.car.service.CarLogService;
import com.lianzai.common.utils.R;
import com.lianzai.mobile.domain.CommunityInfoDO;
import com.lianzai.mobile.service.CarPriceRuleService;
import com.lianzai.mobile.service.CommunityInfoService;
import com.lianzai.stat.service.StatService;
import com.lianzai.util.IpUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/localSystem")
@Controller
public class LocalSystemController {

    @Autowired
    CarLogService carLogService;

    @Autowired
    CommunityInfoService communityInfoService;

    @Autowired
    CarPriceRuleService carPriceRuleService;

    @Autowired
    CameraBlackAndWhiteService cameraBlackAndWhiteService;

    @Autowired
    StatService statService;

    @ResponseBody
    @PostMapping("/syncCarLog")
    public R syncCarLog(@RequestBody CarLogDO carLog)
    {
        if (carLogService.syncLog(carLog) > 0)
        {
            /**
             * 收到同步过来的小区车辆进出信息
             * 出去的时候小区可用车辆加1
             * 进去的时候小区可用车辆减1
             * 2019/07/28
             */
            if(1 == carLog.getDirection()){//进
                statService.subUserPark(carLog.getCommunityId());
            }else if(2 == carLog.getDirection()){//出
                statService.addUserPark(carLog.getCommunityId());
            }
            return R.ok();
        }

        return R.error();
    }

    @ResponseBody
    @PostMapping("/payRequest")
    public R payRequest(@RequestBody Map request)
    {
        //TODO 获取传入参数，需要车牌、小区id、停车时长、费用（可选，如果算费在云端进行，则不必传此值）

        //TODO 调用支付发起方法，与微信支付平台交互，生成订单

        //TODO 返回给本地系统订单号
        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("orderId", "xxxxx");  //TODO 将真实订单填入

        return R.ok(ret);


        //return R.error();
    }

    @ResponseBody
    @GetMapping("/cloudRulelist")
    public JSONObject cloudlist(Long communityId){
        JSONObject obj = new JSONObject();
        try{
            CommunityInfoDO cido = communityInfoService.get(Integer.parseInt(communityId+""));
            if(cido == null){
                obj.put("code","3000");//未找到小区
                obj.put("message","未找到小区");//未找到小区
                return obj;
            }
            String ruleIds = "";
            if(cido.getRuleMonth() != 0){
                if("".equals(ruleIds)){
                    ruleIds = cido.getRuleMonth()+"";
                }else{
                    ruleIds = ruleIds + ","+ cido.getRuleMonth();
                }
            }
            if(cido.getRuleSeason() != 0){
                if("".equals(ruleIds)){
                    ruleIds = cido.getRuleSeason()+"";
                }else{
                    ruleIds = ruleIds + ","+ cido.getRuleSeason();
                }
            }
            if(cido.getRuleTemp() != 0){
                if("".equals(ruleIds)){
                    ruleIds = cido.getRuleTemp()+"";
                }else{
                    ruleIds = ruleIds + ","+ cido.getRuleTemp();
                }
            }
            if(cido.getRuleYear() != 0){
                if("".equals(ruleIds)){
                    ruleIds = cido.getRuleYear()+"";
                }else{
                    ruleIds = ruleIds + ","+ cido.getRuleYear();
                }
            }
            String[] ruleIdsArray = ruleIds.split(",");
            if("".equals(ruleIds)){
                obj.put("code","2000");//未绑定计费规则
                obj.put("message","未绑定计费规则");//未绑定计费规则
                return obj;
            }
            List<Map> carPriceRuleList = carPriceRuleService.cloudlist(ruleIdsArray);
            if(carPriceRuleList == null || carPriceRuleList.size() == 0){
                obj.put("code","4000");//未获取到计费规则
                obj.put("message","获取计费规则失败");//获取计费规则失败
            }else{
                for(int i=0;i<carPriceRuleList.size();i++){
                    Map t_cprdo = carPriceRuleList.get(i);
                    int type = Integer.parseInt(String.valueOf(t_cprdo.get("type")));
                    if(4 == type){//如果是临时规则，查询临时计费规则
                        Long id = Long.parseLong(String.valueOf(t_cprdo.get("id")));
                        List<Map> carPriceRuleSegList = carPriceRuleService.getSegInfo(id);
                        obj.put("ruleSegList",carPriceRuleSegList);
                    }
                }
                obj.put("code","0000");
                obj.put("ruleList",carPriceRuleList);
            }


        }catch(Exception e){
            e.getStackTrace();
            obj.put("code","9999");
            obj.put("message","请求云端数据失败");//请求云端数据失败
        }
        return obj;
    }


    //本地下拉黑白名单
    @ResponseBody
    @GetMapping("/cloudBlackAndWhitelist")
    public JSONObject cloudBlackAndWhitelist(@RequestParam long communityId) {
        //先把原来的记录删除调
        Map map = new HashedMap();
        map.put("communityId",communityId);
        JSONObject retObj = new JSONObject();
        List<Map> blackAndWhiteList =  cameraBlackAndWhiteService.listByCond(map);//数据库记录清除掉
        retObj.put("code","0000");
        retObj.put("blackAndWhiteList",blackAndWhiteList);
        return retObj;
    }

    //本地上报IP
    @ResponseBody
    @GetMapping("/cloudIpRecv")
    public JSONObject cloudIpRecv(@RequestParam long communityId, @RequestParam String token, HttpServletRequest request) {
        /**
         * 查询请求的服务的IP
         */
        JSONObject retObj = new JSONObject();
        CommunityInfoDO cido = communityInfoService.get(Integer.parseInt(communityId+""));
        if(cido == null){
            retObj.put("code","3000");//未找到小区
            retObj.put("message","未找到小区");//未找到小区
            return retObj;
        }
        String  ipAddress = IpUtil.getIpAddress(request);
        if(ipAddress == null || "".equals(ipAddress)){
            retObj.put("code","4000");//未找到小区
            retObj.put("message","IP信息为空");//未找到小区
            return retObj;
        }
        if(!ipAddress.equals(cido.getLocalServerIp())){//如果数据库里面的IP和访问的IP不一致 则更新数据库 达到感知
            cido.setLocalServerIp(ipAddress);
            communityInfoService.update(cido);
        }
        retObj.put("code","0000");
        retObj.put("message","上报IP成功");
        return retObj;
    }
}
